# -*- coding: utf-8 -*-

from flask import render_template, g, request, abort, url_for
from werkzeug.urls import  Href
from datetime import datetime

from google.appengine.api.namespace_manager import get_namespace
from dicthash.decorators import html_it, json_it, glue_GET_POST

from ..backends.working.models import Lenta
from ..backends.working import NotePaginator, NoteByTagPaginator
from .lenta import _proj as _proj_l
from .note  import  _proj_n


def get_all_lentas(namespace):
    """
    Fetches all lentas of a given namespace.
    """
    return [_proj_l(lnt) for lnt in Lenta.all(namespace=namespace)]


def root_page():
    """ """
    if g.user:
        return render_template('lenta/root_logged.html', my_lentas=get_all_lentas(get_namespace()))
    else:
        return render_template('lenta/root_anonymous.html') 


def _browse_lenta(namespace, lenta_id, limit=10, dttm_format='%Y-%m-%d-%H-%M-%S'):
    """
    Browse lenta.
    """
    params = request.args
    
    try:
        dttm = datetime.strptime(params['dttm'], dttm_format) 
    except KeyError:
        dttm = None
    except ValueError:
        abort(404, "Bad format of dttm parameter.")
        
    try:
        limit = int(params.get('limit', limit))
    except ValueError:
        abort(404, "Value for limit parameter must be integer.")    
        
    paginator = NotePaginator(namespace, lenta_id, limit, params.has_key('back'))    
        
    res = paginator(dttm)
    
    href = Href(request.path)
        
    next_page_url = href({'dttm': res.max_dttm.strftime(dttm_format),
                          'limit': limit}) if res.max_dttm else None
                          
    prev_page_url = href({'dttm': res.min_dttm.strftime(dttm_format),
                          'limit': limit, 'back':''}) if res.min_dttm else None
    
    return {
        'next_page_url': next_page_url,
        'prev_page_url': prev_page_url,
        'notes': [_proj_n(note) for note in res.notes]
    }                        

browse_lenta = html_it ('/lenta/browse_lenta.html') (_browse_lenta)
browse_lenta_json = json_it () (_browse_lenta)


def _get_notes_by_tag(namespace, lenta_id, tag_name, limit=10, dttm_format='%Y-%m-%d-%H-%M-%S'):
    """
    Browse notes by tag.
    """
    params = request.args
    
    try:
        dttm = datetime.strptime(params['dttm'], dttm_format) 
    except KeyError:
        dttm = None
    except ValueError:
        abort(404, "Bad format of dttm parameter.")
        
    try:
        limit = int(params.get('limit', limit))
    except ValueError:
        abort(404, "Value for limit parameter must be integer.")
        
    paginator = NoteByTagPaginator(namespace, lenta_id, tag_name, limit, params.has_key('back'))    
        
    res = paginator(dttm)
    
    href = Href(request.path)
    
    next_page_url = href({'dttm': res.max_dttm.strftime(dttm_format),
                          'limit': limit}) if res.max_dttm else None
                          
    prev_page_url = href({'dttm': res.min_dttm.strftime(dttm_format),
                          'limit': limit, 'back':''}) if res.min_dttm else None
    
    return {
        'notes': [_proj_n(note) for note in res.notes],
        'next_page_url': next_page_url,
        'prev_page_url': prev_page_url,
        'tag': {
            'name': tag_name,
            'namespace': namespace,
            'lenta_id': lenta_id
        }
    }

get_notes_by_tag = html_it ('/lenta/note/notes_by_tag.html') (_get_notes_by_tag)
get_notes_by_tag_json = json_it () (_get_notes_by_tag)
